
//对account进行封装和重写
#include <iostream>
#include <pthread.h>

typedef struct
{
    int code;       //账户号码
    double balance; //账户的余额
    //定义一把互斥锁，对多线程操i做的账户进行加锁
    // pthread_mutex_t mutex;
} Account;

class Ac
{

public:
    Ac(double total)
    {

        account = new Account();
        account->code = 1001;
        account->balance = total;
        pthread_mutex_init(&mutex, NULL);
    }

    //取钱
    double withdraw(double amt)
    {
        pthread_mutex_lock(&mutex);
        if (amt < 0 || amt > account->balance)
        {
            pthread_mutex_unlock(&mutex);
            return 0.0;
        }

        double money = account->balance;
        money -= amt;
        account->balance = money;
        pthread_mutex_unlock(&mutex);
        return amt;
    }

    double deposit(double amt)
    {
        pthread_mutex_lock(&mutex);
        if (amt < 0)
        {
            pthread_mutex_unlock(&mutex);
            return 0.0;
        }

        double money = account->balance;
        money += amt;
        pthread_mutex_unlock(&mutex);
        return amt;
    }

    double get_balance()
    {
        pthread_mutex_lock(&mutex);
        double balance = account->balance;
        std::cout << "account:" << balance << std::endl;
        pthread_mutex_unlock(&mutex);
        return balance;
    }

    ~Ac()
    {
        delete account;
        pthread_mutex_destroy(&mutex);
    }

private:
    Account *account;
    pthread_mutex_t mutex;
};
